//
//  WBBaseViewController.swift
//  微博
//
//  Created by 康智桐 on 2018/3/27.
//  Copyright © 2018年 Kk. All rights reserved.
//

import UIKit

class WBBaseViewController: UIViewController {
    
 
    
    //访客视图信息字典
    var visitorInfoDictionary:[String:String]?
    
    
    var tableView:UITableView?
    
    //刷新控件 
    var refreshControl:CZRefreshControl?
    
    
    //上啦刷新标记
    var isPullup = false
    
    //自定义导航条
    lazy var navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: UIScreen.cz_screenWidth(), height: 64))
    //实例化导航条目
    lazy var navItem = UINavigationItem()
    
    override func viewDidLoad() {
        super.viewDidLoad()
 
        
        setupUI()
        
        
        WBNetworkManager.shared.userLogon ? loadData() : ()
        
        
        // 注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(loginSuccess), name: NSNotification.Name(rawValue: WBUserLoginSuccessNotification), object: nil)
        
    }
    //注销通知
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    
    //重写title的didset 
    override var title: String?{
        didSet{
            navItem.title = title
        }
    }
    
    func loadData(){
        //如果子类不实现任何方法，则关闭刷新控件
        refreshControl?.endRefreshing()
    }

}
//访客视图监听方法
extension WBBaseViewController{
   
    @objc func loginSuccess(n:Notification){
        print("登陆成功\(n)")
        
        //导航栏登录成功之后左右按钮
        navItem.leftBarButtonItem = nil
        navItem.rightBarButtonItem = nil
        
        
        //更新ui
         view = nil
     
        //注销通知 避免通知被重复注册
        NotificationCenter.default.removeObserver(self)
        
    }
    
    
    
    @objc  func login(){
        //发送通知
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
        
    }
    @objc  func register(){
        print("用户注册")
    }
    
    
}


extension WBBaseViewController{
    
       func setupUI(){
        
        //取消自动缩进
        automaticallyAdjustsScrollViewInsets = false
        
        view.backgroundColor = UIColor.white
        
        setupNavigationBar()
        
        WBNetworkManager.shared.userLogon ? setupTableView() : setupVisitorView()
            
       
        
        
    }
    
    //设置表格视图
     func setupTableView(){
        
        tableView = UITableView(frame: view.bounds, style: .plain)
        
        view.insertSubview(tableView!, belowSubview: navigationBar)
        
        //设置数据源和代理，目的：子类直接实现数据源方法
        tableView?.dataSource = self
        tableView?.delegate = self
        
        //设置内容缩进
        tableView?.contentInset = UIEdgeInsets(top: navigationBar.bounds.height, left: 0, bottom: tabBarController?.tabBar.bounds.height ?? 49, right: 0)
        
        //修改指示器缩进
        tableView?.scrollIndicatorInsets = (tableView!.contentInset)
        
        
        //设置刷新控件
        //1实例化控件
        refreshControl = CZRefreshControl()
        //添加到视图
        tableView?.addSubview(refreshControl!)
        //t添加监听方法
        refreshControl?.addTarget(self, action: #selector(loadData), for: .valueChanged)
        
    }
    private func setupVisitorView(){
        
        let visitorView = WBVisitorView(frame: view.bounds)
        
        
        view.insertSubview(visitorView, belowSubview: navigationBar)
        
        //设置访客视图
        visitorView.visitorInfo = visitorInfoDictionary
        
        visitorView.loginButton.addTarget(self, action: #selector(login), for: .touchUpInside)
         visitorView.registerButton.addTarget(self, action: #selector(register), for: .touchUpInside)
        
        //设置导航条内容
        navItem.leftBarButtonItem = UIBarButtonItem(title: "注册", style: .plain, target: self, action: #selector(register))
        navItem.rightBarButtonItem = UIBarButtonItem(title: "登录", style: .plain, target: self, action: #selector(login))
        
    }
    
    //设置导航条
    private func setupNavigationBar(){
        //添加导航条
        view.addSubview(navigationBar)
        
        //将Item设置给bar
        navigationBar.items = [navItem ]
        
        //设置navbar整个背景的渲染颜色
        navigationBar.barTintColor = UIColor.cz_color(withHex: 0xF6F6F6)
        
        //设置navbar的字体颜色
        navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.darkGray]
        
        //设置系统按钮的文字渲染颜色
        navigationBar.tintColor = UIColor.orange
        
    }
}

extension WBBaseViewController:UITableViewDataSource,UITableViewDelegate{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 0
    }
    //基类准备方法 ，子类实现方法
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        return UITableViewCell()
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 10
    }
    
    
    //在显示最后一行的时候，做上拉刷新
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        //判断indexPath是否是最后一行
        //取出row
        let row = indexPath.row
        //取出section
        let section = tableView.numberOfSections - 1
        if row < 0 || section < 0 {
            return
        }
        let count = tableView.numberOfRows(inSection: section)
        
        if row == (count - 1) && !isPullup{
            print ("上拉刷新")
            isPullup = true
            
            //开始刷新
            loadData()
        }
        
    }
    
}

